import * as vscode from 'vscode';
import { EntryInfo, Configuration } from '../proto-gen';
import { unix } from 'moment';
import { ProjectEntryApi } from '../proto-gen/api';
import { getProjectToken } from '../utils/tokenUtils';
import { getBasePath } from '../utils/basePathUtils';


export class EntryProvider implements vscode.TreeDataProvider<EntryItem> {
    private _onDidChangeTreeData: vscode.EventEmitter<EntryItem | undefined | void> = new vscode.EventEmitter<EntryItem | undefined | void>();
    readonly onDidChangeTreeData: vscode.Event<EntryItem | undefined | void> = this._onDidChangeTreeData.event;

    getTreeItem(element: EntryItem): vscode.TreeItem | Thenable<vscode.TreeItem> {
        return element;
    }
    getChildren(element?: EntryItem | undefined): vscode.ProviderResult<EntryItem[]> {
        if (element == undefined) {
            return [
                new EntryItem("workPlan"),
                new EntryItem("doc"),
                new EntryItem("draw"),
                new EntryItem("apiColl"),
                new EntryItem("pages"),
            ];
        }
        const basePath = getBasePath();
        if (basePath == null) {
            return [];
        }
        const api = new ProjectEntryApi(new Configuration({
            basePath: basePath.basePath,
        }));
        const tokenInfo = getProjectToken();
        if (tokenInfo == null) {
            return [];
        }
        return new Promise<EntryItem[]>((resolve, _) => {
            api.projectProjectIdEntryEntryTypeGet(tokenInfo.projectId, (element.id ?? "workPlan") as "workPlan" | "doc" | "pages" | "apiColl" | "draw", basePath.token).then(res => {
                const result = res.data.map(item => new EntryItem(item));
                resolve(result);
            }).catch(e => {
                console.log(e);
                vscode.window.showErrorMessage(`${e}`);
                resolve([]);
            });
        });
    }
    sync() {
        this._onDidChangeTreeData.fire();
    }
}

export class EntryItem extends vscode.TreeItem {
    constructor(entryInfo: EntryInfo | "workPlan" | "doc" | "pages" | "apiColl" | "draw") {
        if (typeof entryInfo == "string") {
            if (entryInfo == "workPlan") {
                super("工作文档");
            } else if (entryInfo == "doc") {
                super("项目文档");
            } else if (entryInfo == "pages") {
                super("静态网页");
            } else if (entryInfo == "apiColl") {
                super("接口集合");
            } else if (entryInfo == "draw") {
                super("绘图白板");
            } else {
                super("");
            }

            this.id = entryInfo;
            this.collapsibleState = vscode.TreeItemCollapsibleState.Collapsed;
            this.iconPath = new vscode.ThemeIcon("file-directory");
        } else {
            super(entryInfo.title ?? "");
            this.id = entryInfo.entryId ?? "";
            this.contextValue = 'entry';
            this.collapsibleState = vscode.TreeItemCollapsibleState.None;
            this.iconPath = new vscode.ThemeIcon("file");
            const tooltip = `
            - 创建者: ${entryInfo.createDisplayName ?? ""} 
            - 创建时间: ${entryInfo.createTime == undefined ? "未知" : unix(entryInfo.createTime / 1000).format("YYYY-MM-DD HH:mm:ss")}
                    `;
            this.tooltip = new vscode.MarkdownString(tooltip);
        }
    }

    async show(): Promise<void> {
        const basePath = getBasePath();
        if (basePath == null) {
            return;
        }
        const api = new ProjectEntryApi(new Configuration({
            basePath: basePath.basePath,
        }));
        const tokenInfo = getProjectToken();
        if (tokenInfo == null) {
            return;
        }
        await api.projectProjectIdEntryShowEntryIdGet(tokenInfo.projectId, this.id ?? "", basePath.token);
    }
}